﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HMS.BL;
using HMS.Common;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Collections.Specialized;
using HMS.Security;
using HMS.Logging;

namespace HMS.DL
{
    
    public class Common
    {       
        
        public static string JsonForJqgrid(DataTable dt, int pageSize, int totalRecords, int page)
        {

            try
            {
                int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
                if (dt.TableName == "X_MASTER_LIST_COLUMNS")
                {
                    totalPages = 1;
                    pageSize = totalRecords;
                }              

                StringBuilder jsonBuilder = new StringBuilder();
                jsonBuilder.Append("{");
                jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
                jsonBuilder.Append(":[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{\"id\":" + (i) + ",\"cell\":[");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Rows[i][j].ToString());
                        jsonBuilder.Append("\",");
                    }
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("]},");
                }

                //change by poonam 
                if (dt.Rows.Count != 0)
                {
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                }
                //jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]");
                jsonBuilder.Append("}");
                return jsonBuilder.ToString();
            }
            catch (Exception ex)
            {
                Util.WritErrorLog("$Common$", "JsonForJqgrid", "Error in JsonForJqgrid", "", ex);
                return "false";
                throw ex;
            }
        }

        public static string JsonForJqgrid(DataTable dt,DataTable dtcol,int pageSize, int totalRecords, int page)
        {

            try
            {
                int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
                if (dt.TableName == "X_MASTER_LIST_COLUMNS")
                {
                    totalPages = 1;
                    pageSize = totalRecords;
                }
                //exist

                StringBuilder jsonBuilder = new StringBuilder();
                jsonBuilder.Append("{");
                jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
                jsonBuilder.Append(":[");

            

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{\"id\":" + (i) + ",\"cell\":[");
                    //for (int j = 0; j < dt.Columns.Count; j++)
                    //{
                    //    jsonBuilder.Append("\"");
                    //    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    //    jsonBuilder.Append("\",");
                    //}
                    if (dt.TableName == "exist")
                    {
                        jsonBuilder.Append("\"");
                        // jsonBuilder.Append(dt.Rows[i][j].ToString());
                        jsonBuilder.Append(dt.Rows[i]["REL_ID"].ToString());
                        jsonBuilder.Append("\",");
                    }

                    for (int j = 0; j < dtcol.Rows.Count; j++)
                    {
                        jsonBuilder.Append("\"");                   
                       // jsonBuilder.Append(dt.Rows[i][j].ToString());
                        //if (dt.TableName == "exist" || dt.TableName == "rule")
                        //{
                            jsonBuilder.Append(dt.Rows[i][dtcol.Rows[j]["FIELD_NAME"].ToString()].ToString());
                        //}
                       // else {
                       //     jsonBuilder.Append(dt.Rows[i][dtcol.Rows[j]["name"].ToString()].ToString());
                       // }
                        jsonBuilder.Append("\",");
                    }

                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("]},");
                }
                //change by poonam 
                if (dt.Rows.Count != 0)
                {
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                }
                jsonBuilder.Append("]");
                jsonBuilder.Append("}");
                return jsonBuilder.ToString();
            }
            catch (Exception ex)
            {
                Util.WritErrorLog("$Common$", "JsonForJqgrid(dt,dtcol,,)", "Error in JsonForJqgrid(dt,dtcol,,)", "", ex);
                return "false";
                throw ex;
            }
        }

        public string formDropdownString(string dropval)
        {

            try
            {
                string strVal = string.Empty;
                string[] arr = dropval.Split(',');

                for (int i = 0; i < arr.Length; i++)
                {
                    strVal = strVal + arr[i] + ":" + arr[i] + ";";
                }

                strVal = strVal.Substring(0, strVal.Length - 1);
                return strVal;

            }
            catch (Exception ex)
            {
                Util.WritErrorLog("$Common$", "formDropdownString", "Error in formDropdownString", "", ex);
                throw ex;
            }

        }

        public static string JsonForjqSubgrid(DataTable dt)
        {

            try
            {              
              

                StringBuilder jsonBuilder = new StringBuilder();
                jsonBuilder.Append("{");
                jsonBuilder.Append("\"rows\"");
                jsonBuilder.Append(":[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                   // jsonBuilder.Append("{\"cell\":[");
                    jsonBuilder.Append("{\"row\":[");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("{\"cell\":[");
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Rows[i][j].ToString());
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append("]},");
                    }
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("]},");
                   // jsonBuilder.Append("]},");
                }

                //change by poonam 
                if (dt.Rows.Count != 0)
                {
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                }
                //jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]");
                jsonBuilder.Append("}");
                return jsonBuilder.ToString();
            }
            catch (Exception ex)
            {
                Util.WritErrorLog("$Common$", "JsonForJqgrid", "Error in JsonForJqgrid", "", ex);
                return "false";
                throw ex;
            }
        }

        public Grid SetColModel(Grid griddata, DataTable dt)
        {
            try
            {


                string primarykey = string.Empty;
                List<colModel> listColmodel = new List<colModel>();

                List<string> columns = new List<string>();

                int index = 0;
                //
                foreach (DataRow dr in dt.Rows)
                {

                    //for columns
                    columns.Add(dr["DISPLAY"].ToString());

                    //for colmodel
                    colModel colmodel = new colModel();

                    colmodel.index = dr["FIELD_NAME"].ToString();
                    colmodel.name = dr["FIELD_NAME"].ToString();
                    colmodel.width = 150;
                    colmodel.NullIfEmpty = true;

                    Dictionary<string, object> edoptions = new Dictionary<string, object>();
                    Dictionary<string, object> editrules = new Dictionary<string, object>();
                    Dictionary<string, object> formatoptions = new Dictionary<string, object>();

                    if (Convert.ToString(dr["PRECISION"]) != "")
                    {
                        edoptions.Add("maxlength", Convert.ToInt32(dr["PRECISION"]));
                    }

                    if (Convert.ToString(dr["IS_REQUIRED"]).ToLower() == "true" || Convert.ToInt32(dr["IS_REQUIRED"]) == 1)
                    {
                        editrules.Add("required", true);
                        //if (dt.TableName == "X_HIER_VERSIONS")
                        //{
                        //    formatoptions.Add("elmsuffix", " *");
                        //    formatoptions.Add("rowpos", "1");
                        //    formatoptions.Add("colpos", "2");
                        //}
                    }

                    if (dr["IS_PRIMARY"].ToString().ToLower() == "true" || dr["IS_PRIMARY"].ToString().ToLower() == "1")
                    {

                        primarykey = dr["FIELD_NAME"].ToString();
                        edoptions.Add("required", true);
                        edoptions.Add("edithidden", true);
                        colmodel.key = true;
                        colmodel.editable = false;
                    }
                    else
                    {
                        colmodel.editable = true;
                    }

                    if (dr["DATA_TYPE"].ToString().ToLower() == "number" || dr["DATA_TYPE"].ToString().ToLower() == "int" || dr["DATA_TYPE"].ToString().ToLower() == "real") //integer for whole number
                    {
                        colmodel.sorttype = "int";
                        colmodel.align = "right";

                        editrules.Add("number", true);
                        edoptions.Add("NullIfEmpty", true);
                        //formatter 
                        colmodel.formatter = "number";
                        //format option for number
                        formatoptions.Add("decimalSeparator", ".");
                        formatoptions.Add("thousandsSeparator", string.Empty);
                        //thousandsSeparator
                        formatoptions.Add("defaulValue", 0);
                        formatoptions.Add("decimalPlaces", 2);
                    }
                    else if (dr["DATA_TYPE"].ToString().ToLower() == "varchar" || dr["DATA_TYPE"].ToString().ToLower() == "char" || dr["DATA_TYPE"].ToString().ToLower() == "nvarchar")
                    {
                        colmodel.sorttype = "string";
                        colmodel.align = "left";
                    }
                    else if (dr["DATA_TYPE"].ToString().ToLower() == "date" || dr["DATA_TYPE"].ToString().ToLower() == "datetime")
                    {

                        colmodel.sorttype = "date";
                        colmodel.align = "right";
                        editrules.Add("date", true);
                        colmodel.formatter = "date";
                        //formatoptions.Add("srcformat", "ISO8601Long");                        
                        formatoptions.Add("srcformat", "Y-m-d");//Y-m-d
                        formatoptions.Add("newformat", "m/d/Y");

                    }
                    else if (dr["DATA_TYPE"].ToString().ToLower() == "float")
                    {
                        colmodel.sorttype = "float";
                        colmodel.align = "right";

                        editrules.Add("number", true);
                        edoptions.Add("NullIfEmpty", true);
                        //formatter 
                        colmodel.formatter = "number";
                        //format option for number
                        formatoptions.Add("decimalSeparator", ".");
                        formatoptions.Add("defaulValue", 0);
                        formatoptions.Add("decimalPlaces", 2);
                    }


                    if (dr["DATA_TYPE"].ToString().ToLower() == "bit")
                    {
                        colmodel.edittype = "checkbox";//,editoptions:{value:"Yes:No"} 
                        edoptions.Add("value", "Yes:No");
                        colmodel.formatter = "checkbox";
                    }

                    if (dr["FIELD_NAME"].ToString() == "CONTROL_TYPE")
                    {
                        colmodel.edittype = "select";//editoptions:{value:"FE:FedEx;TN:TNT"}                     
                        string drpval = "textbox:textbox;checkbox:checkbox;textarea:textarea";
                        edoptions.Add("value", drpval); //values in this format
                        edoptions.Add("style", "width:160px");
                        // edoptions.Add("value", "0:Select;FE:FedEx;TN:TNT"); //values in this format
                        edoptions.Add("size", 400);
                    }

                    if (dr["FIELD_NAME"].ToString() == "DATA_TYPE" || dr["FIELD_NAME"].ToString() == "ATTR_DATA_TYPE")
                    {

                        colmodel.edittype = "select";//editoptions:{value:"FE:FedEx;TN:TNT"}
                        string drpval = "nvarchar:nvarchar;varchar:varchar;float:float;int:int;datetime:datetime;char:char;bigint:bigint";
                        edoptions.Add("value", drpval); //values in this format
                        edoptions.Add("style", "width:160px");
                        edoptions.Add("size", 400);
                        //add event to dropdown of datatype

                        //Dictionary<string, object> dataEvents = new Dictionary<string, object>();
                        //dataEvents.Add("type", "change");
                        //object strFun="{ function (e) { alert('hi');} }";
                        //dataEvents.Add("fn", strFun);
                        //edoptions.Add("dataEvents", dataEvents);
                    }


                    if (dr["FIELD_NAME"].ToString() == "PASSWORD")
                    {
                        colmodel.edittype = "password";
                        colmodel.hidden = true;
                        editrules.Add("edithidden", true);
                        //colmodel.e
                    }

                    if (dr["IS_HIDDEN"].ToString() == "1")
                    {
                        colmodel.hidden = true;
                    }

                    //  // A checkbox that may be edited at any time 
                    //{name:'my_checkbox',index:'my_checkbox',
                    //sortable:true,   formatter: "checkbox", 
                    // formatoptions: {disabled : false}, editable: true,  edittype:"checkbox"}
                    if (dr["FIELD_NAME"].ToString() == "xcheckbox")
                    {
                        colmodel.formatter = "checkbox";
                        formatoptions.Add("disabled", false);
                        formatoptions.Add("editable", true);
                        formatoptions.Add("edittype", "checkbox");
                    }
                 
                  
 
                    //{name:'price', index:'price', width:60, align:"center", 
                 //editable: true, formatter:imageFormat, unformat:imageUnFormat},

                    if (dr["FIELD_NAME"].ToString() == "xselect")
                    {

                       // colmodel.formatter = "link";//linkFmatter
                        //colmodel.formatter = "linkFmatter";//linkFmatter

                       // colmodel.formatter = "linkFormatter";
                        colmodel.formatter = "linkFmatter"; //buttonize
                        colmodel.align = "center";
                       // colmodel.editable = true;
                        colmodel.width = 60;
                        //formatoptions.Add("href", "#");                   
                    }

                    ////exception
                    //if (dr["DISPLAY"].ToString().ToUpper() == "TABLE_NAME" || dr["DISPLAY"].ToString() == "IsTableCreated" || dr["DISPLAY"].ToString() == "hasUser")//hasUser
                    //{
                    //    colmodel.hidden = true;
                    //}


                    colmodel.editoptions = edoptions;
                    colmodel.editrules = editrules;
                    colmodel.formatoptions = formatoptions;

                    listColmodel.Add(colmodel);
                    index++;
                }

                griddata.colModelList = listColmodel;
                griddata.columns = columns;
                griddata.primarykey = primarykey;

                return griddata;
            }
            catch (Exception ex)
            {
                Util.WritErrorLog("$ConfigData$", "SetColModel", "Error in SetColModel", "", ex);
                return null;
                throw ex;
            }
        }
    }
}
